﻿// OraVersion.cs
// Aleksei Vassiljev
// {4DC17B88-5237-4e95-A60D-72988F554D4F}

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;

namespace OracleTools.Core
{
    public class OraVersion
    {
        public int? Major { get; set; }
        public int? Release { get; set;}
        public int? Minor { get; set; }
        public int? Build { get; set; }
        public int? Revision { get; set; }

        public OraVersion()
        {
            this.Major = null;
            this.Release = null;
            this.Minor = null;
            this.Build = null;
            this.Revision = null;
        }

        public OraVersion(string version)
        {
            this.Minor = null;
            this.Build = null;
            this.Revision = null;

            if (string.IsNullOrWhiteSpace(version))
            {
                throw new ArgumentNullException("version string");
            }
            string[] strArray = version.Split('.');
            int length = strArray.Length;

            if ((length < 1) || (length > 5))
            {
                throw new ArgumentException("Version is too short or too long");
            }

            for (int i = 0; i < length; i++)
            {
                int nNum;
                int? nnNum = null;
                if (int.TryParse(strArray[i], out nNum))
                    nnNum = nNum;

                if(nnNum != null)
                    if(nnNum.Value < 0)
                        throw new ArgumentOutOfRangeException("version element less than 0");

                switch (i)
                {
                    case 0: this.Major = nnNum; break;
                    case 1: this.Release = nnNum; break;
                    case 2: this.Minor = nnNum; break;
                    case 3: this.Build = nnNum; break;
                    case 4: this.Revision = nnNum; break;
                }
            }
        }
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            if (this.Major.HasValue) sb.Append(this.Major.Value.ToString() + ".");
            if (this.Release.HasValue) sb.Append(this.Release.Value.ToString() + ".");
            if (this.Minor.HasValue) sb.Append(this.Minor.Value.ToString() + ".");
            if (this.Build.HasValue) sb.Append(this.Build.Value.ToString() + ".");
            if (this.Revision.HasValue) sb.Append(this.Revision.Value.ToString() + ".");
            return sb.ToString().TrimEnd('.');
        }

        public bool HasValue
        {
            get { return Major.HasValue; }
        }
    }
}
